using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;

namespace GameLogic
{
    public class GameDataManager : SingletonBehaviour<GameDataManager>
    {
        private Dictionary<string, object> gameData;
        private Dictionary<string, MapDataJson> MapData;
        private float lastSaveTime;
        private const float saveInterval = 30.0f;
        public int defaultSlotCount = 10;
        public int defaultBagCount = 16;
        private static string SavePath => Path.Combine(Application.persistentDataPath, "playerData.json");
        private static string SaveMapDataPath => Path.Combine(Application.persistentDataPath, "TileMapData.json");

        // 从文件加载数据
        public PlayerInfo LoadFromFile()
        {
            if (File.Exists(SavePath))
            {
                string json = File.ReadAllText(SavePath);
                PlayerInfo playerInfo = JsonConvert.DeserializeObject<PlayerInfo>(json);
                return playerInfo;
            }
            else
            {
                
                return InitPlayerInfo();
            }
        }

        public void LoadMapDataFromFile(Action onLoadMapDataComplete=null)
        {
            if (File.Exists(SaveMapDataPath))
            {
                string json = File.ReadAllText(SaveMapDataPath);
                MapData = JsonConvert.DeserializeObject<Dictionary<string, MapDataJson>>(json);
                foreach (var item in MapData)
                {
                    GridMapManager.Instance.InitTileDetailsDict(item.Key, item.Value);
                }
            }
            else
            {

                LoadMapDataFromStreamingAsset(() =>
                {
                    if (MapData == null) return;
                    foreach (var item in MapData)
                    {
                        GridMapManager.Instance.InitTileDetailsDict(item.Key,item.Value);
                    }
                });
            }
        }

        public PlayerInfo InitPlayerInfo()
        {
            PlayerInfo playerInfo = new PlayerInfo();
            playerInfo.itemsSlot = new Dictionary<int, InventoryItem>();
            for (int i = 0; i < defaultSlotCount; i++)
            {
                InventoryItem inventoryItem = new InventoryItem();
                playerInfo.itemsSlot.Add(i, inventoryItem); // 使用槽位ID作为键，默认值作为空槽位
            }
            playerInfo.itemsBag = new Dictionary<int, InventoryItem>();
            for (int i = 0; i < defaultBagCount; i++)
            {
                InventoryItem inventoryItem = new InventoryItem();
                playerInfo.itemsBag.Add(i, inventoryItem); // 使用槽位ID作为键，默认值作为空槽位
            }
            return playerInfo;
        }

        private void LoadMapDataFromStreamingAsset(Action complete=null)
        {
            string sourceDir = Path.Combine(Application.streamingAssetsPath, "TileMapData.json");
            Dictionary<string, MapDataJson> mapJsons;
            LoadTextFileAsync(sourceDir, (data) => { 
                MapData = JsonConvert.DeserializeObject<Dictionary<string, MapDataJson>>(data);
                complete?.Invoke();
            });
            
        }

        private void LoadTextFileAsync(string relativePath, System.Action<string> onComplete)
        {
            StartCoroutine(LoadTextFileCoroutine(relativePath, onComplete));
        }

        private IEnumerator LoadTextFileCoroutine(string relativePath, System.Action<string> onComplete)
        {
            string filePath = Path.Combine(Application.streamingAssetsPath, relativePath);

            using (UnityWebRequest www = UnityWebRequest.Get(filePath))
            {
                yield return www.SendWebRequest();

                if (www.result == UnityWebRequest.Result.Success)
                {
                    onComplete?.Invoke(www.downloadHandler.text);
                }
                else
                {
                    Debug.LogError($"加载失败: {filePath}, 错误: {www.error}");
                    onComplete?.Invoke(null);
                }
            }
        }

        public void SaveToFile()
        {
            if (UserInfo.Instance.playerInfo!=null)
            {
                string json = JsonConvert.SerializeObject(UserInfo.Instance.playerInfo, Formatting.Indented);
                File.WriteAllText(SavePath, json);
                Debug.Log("保存到了这里数据"+SavePath);
            }
        }

        void OnApplicationQuit()
        {
            SaveToFile(); // 退出时确保保存
        }
    }
}
